package com.lovo.user.controller;

import cn.hutool.Hutool;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lovo.common.bean.User;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.ResponseResult;
import com.lovo.common.result.ResultCode;
import com.lovo.common.result.UserValid;
import com.lovo.common.util.JWTUtil;
import com.lovo.common.util.MQUtil;
import com.lovo.user.form.UserForm;
import com.lovo.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.resource.HttpResource;

import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;

@Controller
@RequestMapping("/users")
@Tag(name = "用户管理UserController")
@RefreshScope
public class UserController {
//    @Value("${upload-path}")
    private String uploadPath;
    @Autowired
    private UserService userService;
    @Autowired
    private MQUtil mqUtil;
    @Autowired
    private HttpServletRequest request;

    @PostMapping("/login")
    @Operation(summary = "登录")
    @ResponseResult
    @ResponseBody
    public Object login(@RequestBody UserForm userForm) throws GlobalHandleException {
        System.out.println("uploadPath:" + uploadPath);
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        user.setPwd(DigestUtils.sha256Hex(user.getPwd()));
        user = userService.login(user);
        if(user == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }else{
            String token = JWTUtil.createToken(user.getUsername(),user.getPwd(), Calendar.MINUTE,30);
//            request.setAttribute("user",user);
            return token;
        }

    }
    @PostMapping
    @Operation(summary = "注册")
    @ResponseResult
    @ResponseBody
    public Object register(@RequestBody UserForm userForm){
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        user.setPwd(DigestUtils.sha256Hex(userForm.getPwd()));
        userService.save(user);
        mqUtil.send("shop.direct.exchange","rk.register",user.getId());
        return null;
    }

    @GetMapping("/redirect")
    public Object redirect(Model model,String code){
        // 向gitee获取access_token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code"
                + "&client_id=e394b14116e060213fff87d27f7f4643ad61d216631965f0b079913890e79ea3"
                + "&client_secret=60a7cc8af6210a25e34ff7f89457689fe7d6aa7373556494aaa5d1f2264249db"
                + "&code="+code
                +"&redirect_uri=http://localhost:3000/api/shop-user/users/redirect";
        JSONObject jsonObject = JSONUtil.parseObj(HttpRequest.post(url).execute().body());
        // 从返回的数据中获取access_token
        String accessToken = jsonObject.get("access_token").toString();
        System.out.println("accessToken:" + accessToken);
        // 根据access_token获取用户数据
        jsonObject = JSONUtil.parseObj(HttpRequest.get("https://gitee.com/api/v5/user?access_token=" + accessToken).execute().body());

        // 获取gitee的登录名
        String username = jsonObject.getStr("login");
        // 用此登录名查询当前系统的是否存在这个用户，如果不存在则增加一个
        User user = userService.getByUsername(username);
        String token;
        if(user == null){
            // 用gitee的登录名、密码在当前系统中增加一个用户，密码随机生成
            user = new User();
            user.setUsername(username);
            user.setPwd(DigestUtils.sha256Hex(UUID.randomUUID().toString()));
            user.setEmail(jsonObject.getStr("email"));
            userService.save(user);

        }
        token = JWTUtil.createToken(user.getUsername(),user.getPwd(),Calendar.MINUTE,30);
        model.addAttribute("token",token);
        return "forward.html";


    }
    @GetMapping("/token")
    @UserValid
    @Operation(summary = "从token中获取用户信息")
    @ResponseResult
    @ResponseBody
    public Object getUserInToken() throws GlobalHandleException {
        try {
            String authoriation = request.getHeader(HttpHeaders.AUTHORIZATION);
            String token = authoriation.substring(7);
            String username = JWTUtil.getAudience(token);
            User user = userService.getByUsername(username);
            return user;
        } catch (GlobalHandleException e) {
            throw e;
        }

    }
    @GetMapping("/test")
    @UserValid
    @Operation(summary = "测试")
    @ResponseResult
    @ResponseBody
    public Object test() throws GlobalHandleException {
        return "测试4";

    }
}
